<template>
    <div class="center">
        <img src="../assets/background.png" alt="" class="img" />
        <div class="login">
            <img src="../assets/logos.png" alt="" class="logos" />
            <div class="tab-group">
                <div class="tab-item" :class="{ active: currentTab === 'code' }" @click="currentTab = 'code'">
                    验证码登录
                </div>
                <div class="tab-item" :class="{ active: currentTab === 'password' }" @click="currentTab = 'password'">
                    密码登录
                </div>
                <div class="tab-item" :class="{ active: currentTab === 'scan' }" @click="currentTab = 'scan'">
                    扫码登录
                </div>
            </div>

            <!-- 登录表单 -->
            <div class="login-form">
                <div class="form-group" v-if="currentTab !== 'scan'">
                    <div style="display: flex; flex-direction: column">
                        <p>账号</p>
                        <div class="input-group">
                            <div class="country-code">
                                <select>
                                    <option value="+86 中国大陆" selected>+86</option>
                                    <option value="+852 中国香港">+852</option>
                                    <option value="+853 中国澳门">+853</option>
                                    <option value="+886 中国台湾">+886</option>
                                </select>
                            </div>
                            <input type="text" placeholder="请输入手机号" v-model="phoneNumber" />
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <div style="display: flex; flex-direction: column;">
                        <p v-if="currentTab !== 'scan'">{{ currentTab === 'code' ? '验证码' : '密码' }}</p>
                        <div class="input-group code-group" :class="{
                            'password-input': currentTab === 'password',
                            'scan-input': currentTab === 'scan',
                        }">
                            <!-- 条件渲染：扫码登录时显示图片，否则显示输入框 -->
                            <input v-if="currentTab !== 'scan'" :type="currentTab === 'password' ? 'password' : 'text'"
                                placeholder="请输入验证码或密码" v-model="verificationCode" />
                            <div v-else style="display: flex;flex-direction: column;align-items: center;">
                                <img src="../assets/logo.png" alt="扫码登录" class="qr-code-image" />
                                <p>打开【微信APP】扫一扫进行登录</p>
                            </div>

                            <button class="send-code-btn" v-if="currentTab === 'code'" @click="sendVerificationCode"
                                :disabled="isSending || isCodeExpired">
                                {{ sendButtonText }}
                            </button>
                        </div>
                    </div>
                </div>

                <div class="form-group checkbox-group" v-if="currentTab !== 'scan'">
                    <input type="checkbox" id="auto-login" v-model="autoLogin" />
                    <label for="auto-login">7天自动登录</label>
                </div>

                <div class="form-group checkbox-group" style="margin-top: 80px" v-if="currentTab !== 'scan'">
                    <input type="checkbox" id="agree" v-model="agreed" />
                    <label for="agree">
                        登录即代表同意
                        <a href="#">《用户协议》</a> 和
                        <a href="#">《隐私政策》</a>
                    </label>
                </div>

                <button class="login-btn" @click="handleLogin">登录</button>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { ref } from 'vue';
// 导入路由相关功能
import { useRouter } from 'vue-router';

const router = useRouter(); // 创建路由实例

const currentTab = ref('code');
const phoneNumber = ref('');
const verificationCode = ref('');
const autoLogin = ref(false);
const agreed = ref(false);

// 验证码相关状态
const verificationCodeValue = ref(''); // 存储生成的验证码
const isSending = ref(false); // 是否正在发送验证码
const lastSendTime = ref(0); // 上次发送验证码的时间戳
const codeExpiresAt = ref(0); // 验证码过期时间戳
const isCodeExpired = ref(false); // 验证码是否过期

// 计算属性：发送按钮文本
const sendButtonText = ref('发送验证码');

// 手机号正则验证
function validatePhoneNumber(phone: string): boolean {
    // 中国大陆手机号正则：1开头，11位数字
    const phoneRegex = /^1[3-9]\d{9}$/;
    return phoneRegex.test(phone);
}

// 发送验证码
function sendVerificationCode() {
    // 验证手机号
    if (!phoneNumber.value) {
        alert('请输入手机号');
        return;
    }

    if (!validatePhoneNumber(phoneNumber.value)) {
        alert('请输入正确的手机号');
        return;
    }

    // 检查是否在冷却期内
    const currentTime = Date.now();
    if (currentTime - lastSendTime.value < 60000) { // 1分钟内只能发送一次
        const remainingTime = Math.ceil((60000 - (currentTime - lastSendTime.value)) / 1000);
        alert(`请等待${remainingTime}秒后再试`);
        return;
    }

    // 生成6位随机验证码
    verificationCodeValue.value = Math.floor(100000 + Math.random() * 900000).toString();
    console.log('生成的验证码:', verificationCodeValue.value); // 控制台输出验证码

    // 更新发送状态
    isSending.value = true;
    lastSendTime.value = currentTime;
    codeExpiresAt.value = currentTime + 5 * 60 * 1000; // 5分钟后过期

    // 更新按钮文本
    sendButtonText.value = '60s后重发';

    // 设置倒计时
    let countdown = 60;
    const countdownInterval = setInterval(() => {
        countdown--;
        if (countdown > 0) {
            sendButtonText.value = `${countdown}s后重发`;
        } else {
            clearInterval(countdownInterval);
            isSending.value = false;
            // 检查验证码是否过期
            if (Date.now() < codeExpiresAt.value) {
                sendButtonText.value = '重新发送';
            } else {
                sendButtonText.value = '验证码已过期';
                isCodeExpired.value = true;
            }
        }
    }, 1000);
}

// 处理登录
function handleLogin() {
    if (!phoneNumber.value) {
        alert('请输入手机号');
        return;
    }

    if (!validatePhoneNumber(phoneNumber.value)) {
        alert('请输入正确的手机号');
        return;
    }

    if (currentTab.value === 'code') {
        if (!verificationCode.value) {
            alert('请输入验证码');
            return;
        }

        // 检查验证码是否过期
        if (Date.now() > codeExpiresAt.value) {
            alert('验证码已过期，请重新获取');
            return;
        }

        if (verificationCode.value !== verificationCodeValue.value) {
            alert('验证码错误');
            return;
        }

        if (!agreed.value) {
            alert('请同意用户协议和隐私政策');
            return;
        }
    } else {
        if (!verificationCode.value) {
            alert('请输入密码');
            return;
        }
    }

    console.log('登录中...', {
        phoneNumber: phoneNumber.value,
        verificationCode: verificationCode.value,
        autoLogin: autoLogin.value,
    });

    // 模拟API请求延迟
    setTimeout(() => {
        // 登录成功，生成token
        const token = generateToken();

        // 存储token到本地存储
        if (autoLogin.value) {
            // 如果选择了7天自动登录，将token存储在localStorage中（长期保存）
            localStorage.setItem('token', token);
            localStorage.setItem('phoneNumber', phoneNumber.value);
        } else {
            // 否则存储在sessionStorage中（会话期间有效）
            sessionStorage.setItem('token', token);
            sessionStorage.setItem('phoneNumber', phoneNumber.value);
        }
        console.log('登录成功，生成的token:', token);

        // 跳转到首页
        router.push('/home');
    }, 1000); // 模拟1秒的网络延迟
}

// 生成随机token的函数
function generateToken(): string {
    // 生成一个随机的32位字符串作为token
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let token = '';
    for (let i = 0; i < 32; i++) {
        token += characters.charAt(Math.floor(Math.random() * characters.length));
    }
    return token;
}
</script>
<style scoped>
.center {
    width: 100vw;
    height: 100vh;
    position: relative;
}

.img {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

.login {
    position: absolute;
    background-color: rgb(13, 21, 32);
    right: 10vw;
    top: 20vh;
    color: white;
    width: 24vw;
    height: 60vh;
    border-top: 1px solid;
    border-image: linear-gradient(to right, blue, orange) 0.6;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.logos {
    width: 75%;
    margin: 40px 0;
}

.tab-group {
    width: 80%;
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
    border-bottom: 1px solid #2a3657;
    position: relative;
}

.tab-item {
    padding: 12px 0;
    font-size: 20px;
    color: #8a97b6;
    cursor: pointer;
    position: relative;
    text-align: center;
    flex: 1;
}

.tab-item.active {
    color: #ffffff;
    font-weight: 500;
}

.tab-item.active::after {
    content: '';
    position: absolute;
    bottom: -1px;
    left: 0;
    width: 100%;
    height: 2px;
    background-color: #409eff;
}

.login-form {
    width: 75%;
}

.form-group {
    font-size: 22px;
    margin-bottom: 10px;
}

.input-group {
    display: flex;
    align-items: center;
    background-color: rgb(31, 33, 37);
    border-radius: 8px;
    padding: 0 12px;
    height: 60px;
    width: 100%;
}

.country-code {
    width: 20%;
    position: relative;
}

.country-code::after {
    content: '';
    position: absolute;
    right: 8px;
    top: 50%;
    transform: translateY(-50%);
    border-width: 12px 10px 0 10px;
    border-style: solid;
    border-color: #8a97b6 transparent transparent transparent;
}

.input-group select {
    width: 100%;
    height: 100%;
    background-color: rgb(31, 33, 37);
    border: none;
    outline: none;
    color: #fff;
    appearance: none;
    font-size: 20px;
}

.input-group input {
    flex: 1;
    height: 100%;
    background-color: transparent;
    border: none;
    outline: none;
    color: #fff;
    font-size: 20px;
}

.code-group {
    display: flex;
    width: 100%;
    align-items: center;
}

.code-group input {
    flex: 1;
}

.send-code-btn {
    width: auto;
    padding: 0 10px;
    height: 100%;
    background-color: transparent;
    color: #409eff;
    border: none;
    border-left: 1px solid #364468;
    cursor: pointer;
    font-size: 18px;
    white-space: nowrap;
}

.send-code-btn:disabled {
    color: #8a97b6;
    cursor: not-allowed;
}

.checkbox-group {
    display: flex;
    align-items: center;
    font-size: 15px;
    color: #ccc;
    margin: 20px 0;
}

.checkbox-group input {
    margin-right: 8px;
    width: 16px;
    height: 16px;
    appearance: none;
    background-color: transparent;
    border: 1px solid #409eff;
    border-radius: 2px;
    position: relative;
    cursor: pointer;
}

.checkbox-group input:checked::after {
    content: '';
    position: absolute;
    top: 1px;
    left: 5px;
    width: 3px;
    height: 8px;
    border: solid #409eff;
    border-width: 0 2px 2px 0;
    transform: rotate(45deg) translate(-2px, -1px);
}

.checkbox-group a {
    color: #409eff;
    text-decoration: none;
}

.login-btn {
    position: absolute;
    bottom: 8vh;
    width: 80%;
    height: 50px;
    background-color: #409eff;
    color: #ffffff;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
    margin-top: 10px;
}

/* 新增样式 */
.password-input {
    background-color: rgb(31, 33, 37);
    display: flex;
    justify-content: center;
    align-items: center;
}

.password-input input {
    color: black;
}

.scan-input {
    background-color: transparent;
    display: flex;
    justify-content: center;
    align-items: center;
}

.qr-code-image {
    background-color: white;
    margin-top: 400px;
    width: 250px;
    height: 250px;
    object-fit: contain;
}
</style>